package com.my.thread.pool;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by ZhongGang
 * at 2018/7/20 15:26
 */
public class ExtendWorker extends Worker {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExtendWorker.class);

    private List<Thread> threads;
    private long timeout;
    private TimeUnit unit;

    public ExtendWorker(BlockingQueue<Task> tasks, List<Thread> threads, long timeout, TimeUnit unit) {
        super(tasks);
        this.threads = threads;
        this.timeout = timeout;
        this.unit = unit;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Task task = this.tasks.poll(this.timeout, this.unit);
                if (task == null) {
                    LOGGER.info("arrive the maximum idle time, exit this thread...");
                    synchronized (this.threads) {
                        Iterator<Thread> iterator = this.threads.iterator();
                        while (iterator.hasNext()) {
                            Thread next = iterator.next();
                            if (Objects.equals(next, Thread.currentThread())) {
                                iterator.remove();
                            }
                        }
                    }
                    break;
                }
                task.execute();
            } catch (InterruptedException e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
                break;
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
            }
        }
    }
}
